#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Mini NM data format

Copyright (c) 2014-2015 Christian T. Steigies <steigies@physik.uni-kiel.de>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

This module offers functions to read NM data in ASCII format as used in mininms
and return data in the format as used by NMDB."""

__author__ = "Christian T. Steigies <steigies@physik.uni-kiel.de>"
__license__ = "GPL License"

import os
from datetime import datetime, date, time

from nmdb.station.station_data import check_data, check_pressure
from nmdb.tools.datetool import date2doy, doy2date, mod2time, valid_date
from nmdb.tools.configtool import parse_options

mininm_station = ["neu3", "pol1"]
mininm_long = {
               "neu3": "Neumayer",  # mini NM at Neumayer station
               "pol1": "Polarstern",  # mini NM on Polarstern, 3He counter
#               "pol2": "Polarstern",  # mini NM on Polarstern, BF3 counter
#               "pol3": "Polarstern",  # mini NM on Polarstern, bare counter
               }

## --------------------------------------------------------------------------
def read_rt(options, station, data_type, year, month, day):
    """read realtime data

    options     verbose, dryrun, ...
    station     station short name, must be valid station
    data_type   "1m", "1h", "env", "meta"
    year        integer (1950-9999), may not be None
    month       integer (1-12), if None, read month 1-12
    day         integer (1-31), if None, read day 1-31
    
    return list of values in nmdb format
    """

    if station in mininm_station:
        pass
    else:
        raise ValueError  # wrong station

    value = []
    if valid_date(year, month, day):
        value = read_txt(options, station, data_type, year, month, day)

    return value

## --------------------------------------------------------------------------
def read_rev(options, station, data_type, year, month, day):
    """read revised data

    options     verbose, dryrun, ...
    station     station short name, must be valid station
    data_type   "1m", "1h", "env", "meta"
    year        integer (1950-9999), may not be None
    month       integer (1-12), if None, read month 1-12
    day         integer (1-31), if None, read day 1-31
    
    return list of values in nmdb format
    """

    if station in mininm_station:
        pass
    else:
        raise ValueError  # wrong station

    value = []
    if valid_date(year, month, day):
        value = read_txt(options, station, data_type, year, month, day)

    return value

## --------------------------------------------------------------------------
def read_txt(options, station, data_type, year, month, day):
    """
    read in one day of data and return a list of values from mininm txt file
    use for both real-time and revised data (data is identical)
    """

    value = []
    countrate = [0.1, 10.]
    pressure = [900., 1100.]
    data_path = '~/data/mininm'
    data_path = os.path.expanduser(data_path)

    if data_type in ["1m"]:
        myinterval = 60
    elif data_type in ["1h"]:
        myinterval = 3600
    else:
        raise ValueError  # wrong data_type

    try:
        station_name = mininm_long[station]
    except IndexError:
        return value

    doy = date2doy(date(year, month, day))
    if data_type in ["1m"]:
        filename = "%s/level1/%s/%4i/minute/%4i%03i.txt" \
                % (data_path, station_name, year, year, doy)
    elif data_type in ["1h"]:
        filename = "%s/level1/%s/%4i/hour/%4i%03i.txt" \
                % (data_path, station_name, year, year, doy)
    else:
        return value

    if options.verbose > 1:
        print filename

    try:
        myfile = open(filename, "r")
    except IOError: 
        return value

    line = True
    while line:
        line = myfile.readline()
        #print line
        data = line.split()
        if len(data) < 9:
            break
        year = int(float(data[0]))
        doy = int(float(data[1]))  # day of year
        mydate = doy2date(year, doy)
        if data_type in ["1m"]:
            mod = int(float(data[2]))  # minute of day
            mytime = mod2time(mod)
        elif data_type in ["1h"]:
            hour = int(float(data[2]))  # hour of day
            mytime = time(hour, 0, 0)
        else:
            raise ValueError  # wrong data type
        #one = float(data[3])
        uncorr = float(data[4]) / 60.  # convert counts per minute to counts per second
        #hv = float(data[5])
        #temp = float(data[6])
        press = float(data[7])
        corr_p = float(data[8]) / 60.  # convert counts per minute to counts per second
        corr_e = float(data[9]) / 60.  # convert counts per minute to counts per second
        
        uncorr = check_data(uncorr, cr_min=countrate[0], cr_max=countrate[1])
        press = check_pressure(press, p_min=pressure[0], p_max=pressure[1])
        corr_p = check_data(corr_p, cr_min=countrate[0], cr_max=countrate[1])
        corr_e = check_data(corr_e, cr_min=countrate[0], cr_max=countrate[1])

        mydatetime = datetime.combine(mydate, mytime)

        value.append([mydatetime, myinterval, uncorr, corr_e, corr_p, press])
    return value

## --------------------------------------------------------------------------
def main():
    print "This is the mininm module."

    (options, args) = parse_options("upload")
    if options.verbose > 1:
        print "options:", options
        print "args:", args
    if options.dryrun:
        print "dryrun: not sending any data to NMDB"

    station = "pol1"
    data_type="1h"
    data_type="1m"
    year = 2015
    month = 2
    day = 20

    print station, data_type, year, month, day
    #data = read_rev(options, station, data_type, year, month, day)
    data = read_rt(options, station, data_type, year, month, day)
    for line in data:
        print line

## --------------------------------------------------------------------------
if __name__ == '__main__':
    main()
        